Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 13/43 Β· 161.3 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
how values of various types behave when evaluated in a logical context,
especially in regard to edge cases.cite-ref-14[14] The binary logical operators
returned a Boolean value in early versions of JavaScript, but now they
return one of the operands instead. The left–operand is returned, if it
can be evaluated as : false, in the case of conjunction: (a && b), or
true, in the case of disjunction: (a || b); otherwise the right–operand
is returned. Automatic type coercion by the comparison operators may
differ for cases of mixed Boolean and number-compatible operands
(including strings that can be evaluated as a number, or objects that
can be evaluated as such a string), because the Boolean operand will be
compared as a numeric value. This may be unexpected. An expression can
be explicitly cast to a Boolean primitive by doubling the logical
negation operator: (!!), using the Boolean() function, or using the
conditional operator: (c ? t : f).

// Automatic type coercion
console.log(true == 2 ); // false... true β†’ 1Β !== 2 ← 2
console.log(false == 2 ); // false... false β†’ 0Β !== 2 ← 2
console.log(true == 1 ); // true.... true β†’ 1 === 1 ← 1
console.log(false == 0 ); // true.... false β†’ 0 === 0 ← 0
console.log(true == "2"); // false... true β†’ 1Β !== 2 ← "2"
console.log(false == "2"); // false... false β†’ 0Β !== 2 ← "2"
console.log(true == "1"); // true.... true β†’ 1 === 1 ← "1"
console.log(false == "0"); // true.... false β†’ 0 === 0 ← "0"
console.log(false == "" ); // true.... false β†’ 0 === 0 ← ""
console.log(false == NaN); // false... false β†’ 0Β !== NaN
console.log(NaN == NaN); // false...... NaN is not equivalent to
anything, including NaN.
// Type checked comparison (no conversion of types and values)
console.log(true === 1); // false...... data types do not match
// Explicit type coercion
console.log(true === !!2); // true.... data types and values match
console.log(true === !!0); // false... data types match, but values
differ
console.log( 1 ? true : false); // true.... only Β±0 and NaN are "falsy"
numbers
console.log("0" ? true : false); // true.... only the empty string is
"falsy"
console.log(Boolean({})); // true.... all objects are "truthy"

The new operator can be used to create an object wrapper for a Boolean
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────